package servlet.events;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.PaginationHandler;

import model.Recipe;

import dao.DAOFactory;

public class SearchRecipeHandler extends EventHandler {
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//get keyword
		String keyword = request.getParameter("keyword");

		//get category_id
		int category_id = 0;
		try {
			category_id = Integer.parseInt(request.getParameter("category")); //ex!
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		
		//get recipe total list
		List<Recipe> recipeList = DAOFactory.getRecipeDAO().search(keyword, category_id);		
		
		/**
		 * do Pagination
		 */
		
		PaginationHandler<Recipe> paginationHandler = new PaginationHandler<Recipe>(recipeList);
		//paginationHandler.setLength(5); //by default, max entries per page = 5 
		
		//get page value
		String pageNumberValue = request.getParameter("page");		
		int pageNumber = 1;
		if (pageNumberValue != null) {
			try {
				pageNumber = Integer.parseInt(pageNumberValue);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			}
		}
		
		//set recipe total number
		request.setAttribute("recipeTotalNumbers", paginationHandler.getListTotalNumbers());
		//set page numbers list
		request.setAttribute("pageNumbers", paginationHandler.getPageNumbers());
		//set recipeList per page
		request.setAttribute("recipeListPP", paginationHandler.getList(pageNumber));
		
		forward(urlBundle.getString("SEARCH_URL"), request, response);
	}
}
